import React, { Component } from 'react'
import { Button, WingBlank, InputItem, List, WhiteSpace, Picker, Toast, TextareaItem, Switch, ImagePicker } from 'antd-mobile'
import getData from '../../server/GetData'
import uuid from '../../server/UUIDUtils'
import { getSearchParams } from '../../utils/param'
import { expPhone } from '../../utils/utils'
import Compressor from '../../utils/Compressor'
import axios from 'axios'
import './index.css'

export default class index extends Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '',
            room: '',
            phone: '',
            eventObject: '',
            eventDesc: '',
            isAnonymous: false,
            // 科室
            depData: [],
            depMZData: [],
            depZYData: [],
            depValue: '',
            depLabel: '',
            // 事件类型
            eventType: [{
                value: 1,
                label: '投诉',
            }, {
                value: 2,
                label: '表扬',
            }],
            eventTypeValue: '',
            eventTypeLabel: '',
            // 类别
            eventObjectType: [{
                value: 1,
                label: '医疗',
            }, {
                value: 2,
                label: '护理',
            }, {
                value: 3,
                label: '服务',
            }, {
                value: 4,
                label: '医技',
            }, {
                value: 5,
                label: '其他',
            }],
            eventObjectTypeValue: '',
            eventObjectTypeLabel: '',
            // 投诉目的
            eventObjectGoal1: [{
                value: 1,
                label: '提出建议/望改进',
            }, {
                value: 2,
                label: '咨询了解',
            }, {
                value: 3,
                label: '望能给予合理解释',
            }, {
                value: 5,
                label: '要求索赔',
            }],
            eventObjectGoal1Value: '',
            eventObjectGoal1Label: '',
            eventObjectGoal2: [{
                value: 1,
                label: '望传达表扬',
            }, {
                value: 2,
                label: '望嘉奖',
            }, {
                value: 3,
                label: '望树立典型',
            }],
            eventObjectGoal2Value: '',
            eventObjectGoal2Label: '',
            // 患者类别
            patientType: [{
                value: 1,
                label: '门急诊患者',
            }, {
                value: 2,
                label: '住院患者',
            }],
            patientTypeValue: '',
            patientTypeLabel: '',
            // 图片
            files: [],
            urlArr: []
        }
    }
    onChangeEventType(v) {
        let label = '';
        this.state.eventType.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            eventTypeValue: v,
            eventTypeLabel: label
        })
    }
    onChangeEventObjectType(v) {
        let label = '';
        this.state.eventObjectType.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            eventObjectTypeValue: v,
            eventObjectTypeLabel: label
        })
    }
    onChangeEventObjectGoal1(v) {
        let label = '';
        this.state.eventObjectGoal1.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            eventObjectGoal1Value: v,
            eventObjectGoal1Label: label
        })
    }
    onChangeEventObjectGoal2(v) {
        let label = '';
        this.state.eventObjectGoal2.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            eventObjectGoal2Value: v,
            eventObjectGoal2Label: label
        })
    }
    onChangePatientType(v) {
        let label = '';
        this.state.patientType.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            patientTypeValue: v,
            patientTypeLabel: label,
            depValue: '',
            depLabel: ''
        })
    }
    onChangeDep(v) {
        let label = '';
        this.state.depData.forEach(item => {
            if (item.value == v) {
                label = item.label
            }
        })
        this.setState({
            depValue: v,
            depLabel: label
        })
    }
    selectImg(files, type, index) {
        let that = this
        console.log(files, type, index);
        if (type === 'add') {
            this.upload(files[files.length - 1].url, function (res) {
                let url = res.data?.data || ''
                if (!url) return
                that.setState({
                    files,
                    urlArr: [...that.state.urlArr, url]
                });
            })
        } else if (type === 'remove') {
            let arr = [].concat(that.state.urlArr)
            arr.splice(index, 1)
            that.setState({
                files,
                urlArr: arr
            })
        }
    }
    upload(url, cb) {
        let that = this
        let file1 = this.dataURLtoBlob(url)
        this.uploadImg(file1, cb)
        // Compressor.fileResizetoFile(file1, 1, function(file2){
        //     that.uploadImg(file2, cb)
        // })
    }
    uploadImg(file, cb) {
        let param = new FormData()
        param.append('file', file, 'head.jpg')
        param.append('name', 'biz')
        Toast.loading('图片上传中...')
        axios({
            method: "post",
            url: 'http://bizser.njtrh.org:9991/upload/uploadImage?name=biz',
            // url: 'http://bizser.njtrh.org:9991/upload/uploadImage?name=biztd', // 测试用
            data: param
        }).then(res => {
            Toast.success('图片上传成功', 1)
            cb(res)
        }).catch(err => {
            Toast.fail('上传图片失败', 2)
        })
    }

    proDownImage(path, imgObj) { // 等比压缩图片工具 
        //var proMaxHeight = 185; 
        var proMaxHeight = 300;
        var proMaxWidth = 175;
        var size = new Object();
        var image = new Image();
        image.src = path;
        image.attachEvent("onreadystatechange", function () { // 当加载状态改变时执行此方法,因为img的加载有延迟 
            if (image.readyState == "complete") { // 当加载状态为完全结束时进入 
                if (image.width > 0 && image.height > 0) {
                    var ww = proMaxWidth / image.width;
                    var hh = proMaxHeight / image.height;
                    var rate = (ww < hh) ? ww : hh;
                    if (rate <= 1) {
                        alert("imgage width*rate is:" + image.width * rate);
                        size.width = image.width * rate;
                        size.height = image.height * rate;
                    } else {
                        alert("imgage width is:" + image.width);
                        size.width = image.width;
                        size.height = image.height;
                    }
                }
            }
            imgObj.attr("width", size.width);
            imgObj.attr("height", size.height);
        });
    }
    imagetoCanvas(image) {
        var cvs = document.createElement("canvas");
        var ctx = cvs.getContext('2d');
        cvs.width = image.width;
        cvs.height = image.height;
        ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
        return cvs;
    };
    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(',');
        //注意base64的最后面中括号和引号是不转译的   
        var _arr = arr[1].substring(0, arr[1].length - 2);
        var mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(_arr),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }
    onSubmit() {
        let that = this
        // 提交投诉内容
        let params = {}
        params.name = this.state.name
        params.phone = this.state.phone.replace(/\s*/g, "")
        params.eventType = this.state.eventTypeValue[0]
        params.eventObjectType = this.state.eventObjectTypeValue[0]
        params.eventObject = this.state.eventObject
        params.eventObjectGoal = this.state.eventTypeValue == 1 ? this.state.eventObjectGoal1Value[0] : this.state.eventObjectGoal2Value[0]
        params.patientType = this.state.patientTypeValue[0]
        params.eventDesc = this.state.eventDesc
        params.eventDeptName = this.state.depLabel
        params.eventDeptId = this.state.depValue[0]
        params.isAnonymous = this.state.isAnonymous ? 1 : 2
        // params.fildUrl1 = this.state.files[0].url
        for (let i = 0; i < this.state.urlArr.length; i++) {
            params['fildUrl' + (i + 1)] = this.state.urlArr[i]
        }
        let flag = true;
        Object.keys(params).forEach(item => {
            if (item.indexOf('fildUrl') === -1 && !params[item]) flag = false
        })
        if (!flag) {
            Toast.info('请完整填写内容', 2)
            return
        }
        if (!expPhone(params.phone)) {
            Toast.info('请填写正确手机号', 2)
            return
        }
        Toast.loading('提交中...', 30, () => { });

        getData({
            data: {
                bizContent: params,
                method: 'saveComplaint',
                bizId: uuid()
            }
        }).then(res => {
            if (res.rspCode != 200) {
                Toast.info(res.rspMsg, 2);
            } else if (res.bizRspCode != 1) {
                Toast.info(res.bizRpsMsg, 2);
            } else {
                Toast.info('提交成功！', 2, function () {
                    that.props.history.replace({
                        pathname: '/result',
                        search: `?resultMsg=${encodeURIComponent((params.eventType == 1 ? '投诉' : '表扬') + '内容提交成功!')}`
                    })
                })
            }
        }).catch(err => {
            Toast.info(err)
        })
    }
    componentDidMount() {
        document.title = '用户投诉与表扬'

        let hosCode = localStorage.getItem('hosCode')
        if (hosCode === '003' ||
            hosCode === '004' ||
            hosCode === '005' ||
            hosCode === '006') {
            this.setState({
                hasAnony: false,
            })
        } else {
            this.setState({
                hasAnony: true,
            })
        }

        getData({
            data: {
                bizContent: {},
                method: 'getDeptInfo',
                bizId: uuid()
            }
        }).then(res => {
            if (res.rspCode != 200) {
                Toast.info(res.rspMsg, 2);
            } else if (res.bizRspCode != 1) {
                Toast.info(res.bizRpsMsg, 2);
            } else {
                let bizContent = res.bizContent || ''
                let depList = JSON.parse(bizContent).deptList
                let depData = []
                let depMZData = []
                let depZYData = []
                depList.forEach(dep => {
                    depData.push({
                        value: dep.id,
                        label: dep.deptName
                    })
                    if (dep.deptType === 'mz') {
                        depMZData.push({
                            value: dep.id,
                            label: dep.deptName
                        })
                    } else if (dep.deptType === 'zy') {
                        depZYData.push({
                            value: dep.id,
                            label: dep.deptName
                        })
                    }
                })
                this.setState({
                    depData,
                    depMZData,
                    depZYData
                })
            }
        }).catch(err => {
            Toast.hide()
        })
    }
    render() {
        return (
            <div className="questComp-class">
                <WingBlank>
                    <List renderHeader="您的姓名">
                        <InputItem onBlur={v => this.setState({ name: v })} />
                    </List>
                    <List renderHeader="房号">
                        <InputItem onBlur={v => this.setState({ room: v })} />
                    </List>
                    <List renderHeader="手机号码">
                        <InputItem onBlur={v => this.setState({ phone: v })} type="phone" />
                    </List>
                    <List renderHeader="患者类别">
                        <Picker
                            data={this.state.patientType}
                            cols="1"
                            value={this.state.patientTypeValue}
                            onChange={v => this.onChangePatientType(v)}
                        >
                            <List.Item arrow="horizontal">{this.state.patientTypeLabel}</List.Item>
                        </Picker>
                    </List>
                    <List renderHeader="表扬/投诉科室">
                        {
                            this.state.patientTypeValue == 1 ?
                                <Picker
                                    data={this.state.depMZData}
                                    cols="1"
                                    value={this.state.depValue}
                                    onChange={v => this.onChangeDep(v)}
                                >
                                    <List.Item arrow="horizontal">{this.state.depLabel}</List.Item>
                                </Picker>
                                :
                                <Picker
                                    data={this.state.depZYData}
                                    cols="1"
                                    value={this.state.depValue}
                                    onChange={v => this.onChangeDep(v)}
                                >
                                    <List.Item arrow="horizontal">{this.state.depLabel}</List.Item>
                                </Picker>
                        }
                    </List>
                    <List renderHeader="表扬/投诉">
                        <Picker
                            data={this.state.eventType}
                            cols="1"
                            value={this.state.eventTypeValue}
                            onChange={v => this.onChangeEventType(v)}
                        >
                            <List.Item arrow="horizontal">{this.state.eventTypeLabel}</List.Item>
                        </Picker>
                    </List>
                    <List renderHeader="表扬/投诉对象">
                        <InputItem onBlur={v => this.setState({ eventObject: v })} />
                    </List>
                    <List renderHeader="表扬/投诉对象类别">
                        <Picker
                            data={this.state.eventObjectType}
                            cols="1"
                            value={this.state.eventObjectTypeValue}
                            onChange={v => this.onChangeEventObjectType(v)}
                        >
                            <List.Item arrow="horizontal">{this.state.eventObjectTypeLabel}</List.Item>
                        </Picker>
                    </List>
                    <List renderHeader="表扬/投诉目的">
                        {
                            this.state.eventTypeValue == 1 ?
                                <Picker
                                    data={this.state.eventObjectGoal1}
                                    cols="1"
                                    value={this.state.eventObjectGoal1Value}
                                    onChange={v => this.onChangeEventObjectGoal1(v)}
                                >
                                    <List.Item arrow="horizontal">
                                        {this.state.eventObjectGoal1Label}
                                    </List.Item>
                                </Picker>
                                :
                                <Picker
                                    data={this.state.eventObjectGoal2}
                                    cols="1"
                                    value={this.state.eventObjectGoal2Value}
                                    onChange={v => this.onChangeEventObjectGoal2(v)}
                                >
                                    <List.Item arrow="horizontal">
                                        {this.state.eventObjectGoal2Label}
                                    </List.Item>
                                </Picker>
                        }
                    </List>
                    <List renderHeader="表扬/投诉内容描述">
                        {/* <InputItem onBlur={v => this.setState({eventDesc: v})}/> */}
                        <TextareaItem
                            onBlur={v => this.setState({ eventDesc: v })}
                            rows={5}
                            count={500}
                        />
                    </List>
                    <List renderHeader="上传图片">
                        <ImagePicker
                            files={this.state.files}
                            onChange={(fs, type, i) => this.selectImg(fs, type, i)}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            selectable={this.state.files.length < 6}
                            multiple={false}
                        />
                    </List>
                    {
                        this.state.hasAnony ?
                            <List renderHeader="是否匿名">
                                <List.Item
                                    extra={<Switch
                                        checked={this.state.isAnonymous}
                                        onChange={() => {
                                            this.setState({
                                                isAnonymous: !this.state.isAnonymous
                                            });
                                        }}
                                    />}
                                >{this.state.isAnonymous ? '匿名' : '不匿名'}</List.Item>
                            </List>
                            :
                            <div></div>
                    }
                    <WhiteSpace size="xl" />
                    <WhiteSpace size="lg" />
                    <div onClick={v => this.onSubmit()} className="btn-next" type="primary">提交</div>
                </WingBlank>
            </div>
        )
    }
}
